package com.donlim.dev.utils;

import com.donlim.dev.entity.SysUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 星 on 2020/11/3
 * jwt Token 工具类
 */
@Slf4j
@Component
public class JwtTokenUtil {

    private final String CLAIMS_KEY_USERCODE = "sub";
    private final String CLAIMS_KEY_CREATED = "created";
    @Value("${jwt.secret}")
    private String secret; //密钥
    @Value("${jwt.expiration}")
    private Long expiration; //超时时间

    /**
     * 根据负载生成token
     * @param claims
     * @return
     */
    private String generateToken(Map<String,Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpiration())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    /**
     * 根据用户信息生成token
     * @param sysUser
     * @return
     */
    public String generateToken(SysUser sysUser){
        HashMap<String,Object> claims = new HashMap<>();
        claims.put(CLAIMS_KEY_USERCODE,sysUser.getUserCode());
        claims.put(CLAIMS_KEY_CREATED,new Date());
        return generateToken(claims);
    }

    /**
     * 从token中获取负载信息
     * @param token
     * @return
     */
    public Claims getClaimsFromToken(String token){
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            log.info("JWT格式验证失败，{}",token);
        }
        return claims;
    }

    /**
     * 从token中获取userCode
     * @param token
     * @return
     */
    public String getUserCodeFromToken(String token){
        String userCode;
        try {
            Claims claims = getClaimsFromToken(token);
            userCode = claims.getSubject();
        }catch (Exception e){
            userCode = null;
        }
        return userCode;
    }

    /**
     * 验证token是否有效
     * @param token
     * @param sysUser
     * @return
     */
    public boolean validateToken(String token,SysUser sysUser){
        String userCode = getUserCodeFromToken(token);
        return userCode.equals(sysUser.getUserCode()) && !isTokenExpired(token);
    }


    /**
     * 判断token是否失效
     * @param token
     * @return
     */
    private boolean isTokenExpired(String token){
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     * @param token
     * @return
     */
    private Date getExpiredDateFromToken(String token){
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 生成token过期时间
     * @return
     */
    private Date generateExpiration(){
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 刷新token时间
     * @param oldToken
     * @return
     */
    public String refreshHeadToken(String oldToken){
        if (StringUtils.isEmpty(oldToken)){
            return null;
        }
        if (StringUtils.isEmpty(oldToken)){
            return null;
        }
        //token验证不通过
        Claims claims = getClaimsFromToken(oldToken);
        if (claims == null){
            return null;
        }
        //token过期不支持刷新
        if (isTokenExpired(oldToken)){
            return null;
        }
        claims.put(CLAIMS_KEY_CREATED,new Date());
        return generateToken(claims);
    }

    /**
     * 判断token是否在指定时间内刷新过
     * @param token
     * @param time 指定时间 秒
     * @return
     */
    private boolean tokenRefreshJustBefore(String token,int time){
        return false;
    }

}
